<template>
  <div class="page-order-refund">
    <div class="search-bar">
      <el-form
        :inline="true"
        @submit.prevent
        @keyup.enter="onGetDataList(page)"
      >
        <div class="input-row">
          <el-form-item :label="$t('order.refundId') + '：'">
            <el-input
              v-model="searchForm.refundSn"
              :placeholder="$t('order.refundId')"
              clearable
            />
          </el-form-item>
          <el-form-item :label="$t('order.afterSalesStatus') + '：'">
            <el-select
              v-model="returnMoneySts"
              clearable
              :placeholder="$t('order.pleSelAfterSalesSta')"
              @change="onOrderRefundStatus"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('order.typeOfRefund') + '：'">
            <el-select
              v-model="searchForm.refundType"
              clearable
              :placeholder="$t('order.typeOfRefund')"
            >
              <el-option
                v-for="item in refundType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('order.number') + '：'">
            <el-input
              v-model="searchForm.orderNumber"
              :placeholder="$t('order.number')"
              clearable
            />
          </el-form-item>
          <el-form-item :label="$t('order.orderType') + '：'">
            <el-select
              v-model="searchForm.orderType"
              clearable
              :placeholder="$t('order.pleaseSelectOrderType')"
            >
              <el-option
                v-for="item in orderType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('order.applicationType') + '：'">
            <el-select
              v-model="searchForm.applyType"
              clearable
              :placeholder="$t('order.pleaseChooseHowToApply')"
            >
              <el-option
                v-for="item in applyType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('order.createTime') + '：'">
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              range-separator="-"
              value-format="YYYY-MM-DD HH:mm:ss"
              :start-placeholder="$t('date.start')"
              :end-placeholder="$t('date.end')"
              :default-time="defaultTime"
            />
            <div class="operation-box">
              <div
                class="default-btn"
                @click="onSetDateRange(1)"
              >
                {{ $t('date.t') }}
              </div>
              <div
                class="default-btn"
                @click="onSetDateRange(2)"
              >
                {{ $t('date.y') }}
              </div>
              <div
                class="default-btn"
                @click="onSetDateRange(3)"
              >
                {{ $t('date.n') }}
              </div>
              <div
                class="default-btn"
                @click="onSetDateRange(4)"
              >
                {{ $t('m') }}
              </div>
            </div>
          </el-form-item>
          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="onSearch(true)"
            >
              {{ $t('order.query') }}
            </div>
            <div
              class="default-btn"
              @click="onResetSearch()"
            >
              {{ $t('temp.setNull') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="main">
      <div class="content">
        <!-- 导航 -->
        <div class="status-nav clearfix">
          <ul
            :class="['clearfix', $t('language') === 'English' ? 'nav-list-ul-en' : 'nav-list-ul-zh']"
          >
            <li
              :class="['nav-item-li', sts === 0 ? 'selected' : '']"
              data-sts="0"
              @click="onSelectNav($event)"
            >
              {{ $t('date.a') }}
            </li>
            <li
              :class="['nav-item-li', sts === 1 ? 'selected' : '']"
              data-sts="1"
              @click="onSelectNav($event)"
            >
              {{ $t('order.buyerApplication') }}
            </li>
            <li
              :class="['nav-item-li', sts === 2 ? 'selected' : '']"
              data-sts="2"
              @click="onSelectNav($event)"
            >
              {{ $t('order.sellerAccepts') }}
            </li>
            <li
              :class="['nav-item-li', sts === 3 ? 'selected' : '']"
              data-sts="3"
              @click="onSelectNav($event)"
            >
              {{ $t('order.buyShipment') }}
            </li>
            <li
              :class="['nav-item-li', sts === 4 ? 'selected' : '']"
              data-sts="4"
              @click="onSelectNav($event)"
            >
              {{ $t('order.sellerReceipt') }}
            </li>
            <li
              :class="['nav-item-li', sts === 5 ? 'selected' : '']"
              data-sts="5"
              @click="onSelectNav($event)"
            >
              {{ $t('order.refundsuccessfully') }}
            </li>
            <li
              :class="['nav-item-li', sts === -1 ? 'selected' : '']"
              data-sts="-1"
              @click="onSelectNav($event)"
            >
              {{ $t('order.refundClosed') }}
            </li>
          </ul>
          <ul class="nav-right" />
        </div>

        <!-- 列标题 -->
        <div
          :class="['tit', showHeadScroll ? 'fixed-top' : '']"
          :style="{
            width: !showHeadScroll ? '100%' : sidebarFold ? 'calc(83.5% + 130px )' : '83.5%'
          }"
        >
          <el-row
            style="width: 100%"
            class="col-wrap"
          >
            <el-col :span="productSpan">
              <span class="item product">{{ $t('home.product') }}</span>
            </el-col>
            <el-col
              :span="3"
              class="transaction-price"
              :class="$t('language') === 'English' && showHeadScroll ? 'mediaStytle' : ''"
            >
              <span class="item">{{ $t('order.commodityUnitPriceYuanQuantity') }}</span>
            </el-col>
            <el-col
              :span="3"
              class="column-title"
            >
              <span class="item">{{ $t('order.returnAmount') }}({{ $t('admin.dollar') }})</span>
            </el-col>
            <el-col
              :span="3"
              class="column-title"
            >
              <span class="item">{{ $t('order.commodityCondition') }}</span>
            </el-col>
            <el-col
              :span="2"
              class="column-title"
            >
              <span class="item">{{ $t('order.typeOfRefund') }}</span>
            </el-col>
            <el-col
              :span="2"
              class="column-title"
            >
              <span class="item">{{ $t('group.orderStatus') }}</span>
            </el-col>
            <el-col
              :span="2"
              class="column-title"
            >
              <span class="item">{{ $t('order.afterSalesStatus') }}</span>
            </el-col>
            <el-col
              :span="2"
              class="column-title"
            >
              <span class="item">{{ $t('publics.operating') }}</span>
            </el-col>
          </el-row>
        </div>

        <div
          v-for="orderRefund in dataList"
          :key="orderRefund.refundId"
          class="prod"
        >
          <div :class="['prod-tit']">
            <span>{{ $t('order.refundId') }}：{{ orderRefund.refundSn }}</span>
            <span>{{ $t('order.number') }}：{{ orderRefund.orderNumber }}</span>
            <span>{{ $t('order.applicationTime') }}：{{ orderRefund.applyTime }}</span>
          </div>
          <div class="prod-cont">
            <el-row style="width: 100%">
              <el-col
                :span="$t('language') === 'English' ? 9 : 10"
                style="height: 100%"
              >
                <div class="prod-item">
                  <div
                    v-for="orderItem in orderRefund.orderItems"
                    :key="orderItem.orderItemId"
                    class="items name"
                  >
                    <div class="prod-image">
                      <ImgShow :src="orderItem.pic" />
                    </div>
                    <div class="prod-name">
                      <div class="prod-con">
                        <div class="prod-name-txt">
                          {{ orderItem.prodName }}
                        </div>
                        <div
                          v-if="orderRefund.orderType === 1 || orderRefund.orderType === 2"
                          class="order-status"
                        >
                          {{
                            orderRefund.orderType === 1
                              ? $t('order.groupPurchaseOrder')
                              : orderRefund.orderType === 2
                                ? $t('order.spikeOrder')
                                : ''
                          }}
                        </div>
                        <div
                          v-if="orderRefund.dvyType === 2 || orderRefund.dvyType === 4"
                          class="order-status"
                        >
                          {{
                            orderRefund.dvyType === 2
                              ? $t('order.selfMention')
                              : orderRefund.dvyType === 4
                                ? $t('order.sameCityDelivery')
                                : ''
                          }}
                        </div>
                      </div>
                    </div>
                    <div class="prod-price">
                      <span>{{ orderItem.price.toFixed(2) }}</span>
                      <span>{{ orderItem.prodCount }}{{ $t('marketing.item') }}</span>
                    </div>
                  </div>
                </div>
              </el-col>
              <el-col
                :span="3"
                style="height: 100%"
              >
                <div class="item">
                  <div>
                    <span class="totalprice">{{
                      orderRefund.refundAmount.toFixed(2) +
                        ' + ' +
                        orderRefund.refundScore +
                        $t('order.integral')
                    }}</span>

                    <span v-if="orderRefund.goodsNum > 0">{{ $t('order.total') }}{{ orderRefund.goodsNum
                    }}{{ $t('marketing.item') }}</span>
                  </div>
                </div>
              </el-col>
              <el-col
                :span="3"
                style="height: 100%"
              >
                <div class="item">
                  <div class="buyer-info">
                    <span>{{
                      orderRefund.applyType === 1 ? $t('order.onlyRefund') : $t('order.refunds')
                    }}</span>
                    <span class="totalprice">{{
                      orderRefund.isReceiver
                        ? $t('order.goodsReceived')
                        : $t('order.goodsNotReceived')
                    }}</span>
                    <div
                      class="totalprice"
                      style="color: #333333; margin-bottom: 4px"
                    >
                      {{ orderRefund.buyerReason }}
                    </div>
                  </div>
                </div>
              </el-col>
              <el-col
                :span="2"
                style="height: 100%"
              >
                <div class="item">
                  <div>
                    <span v-if="orderRefund.refundType === 1">{{
                      $t('order.wholeGoodsRefund')
                    }}</span>
                    <span v-if="orderRefund.refundType === 2">{{
                      $t('order.singleItemRefund')
                    }}</span>
                  </div>
                </div>
              </el-col>
              <el-col
                :span="2"
                style="height: 100%"
              >
                <div class="item">
                  <span
                    v-if="orderRefund.status === 1"
                    type="danger"
                  >{{
                    $t('order.pendingPayment')
                  }}</span>
                  <span
                    v-else-if="orderRefund.status === 2"
                    type="danger"
                  >{{
                    $t('order.toBeShipped')
                  }}</span>
                  <span
                    v-else-if="orderRefund.status === 3"
                    type="danger"
                  >{{
                    $t('order.pendingReceipt')
                  }}</span>
                  <span
                    v-else-if="orderRefund.status === 7"
                    type="danger"
                  >{{
                    $t('group.waitGroup')
                  }}</span>
                  <span
                    v-else-if="orderRefund.status === 5"
                    type="danger"
                  >{{
                    $t('order.successfulTransaction')
                  }}</span>
                  <span v-else-if="orderRefund.status === 6">{{
                    $t('order.transactionFailed')
                  }}</span>
                </div>
              </el-col>
              <el-col
                :span="2"
                style="height: 100%"
              >
                <div class="item">
                  <span
                    v-if="orderRefund.returnMoneySts === 1"
                    type="danger"
                  >{{
                    $t('order.buyerApplication')
                  }}</span>
                  <span
                    v-else-if="orderRefund.returnMoneySts === 2"
                    type="danger"
                  >{{
                    $t('order.sellerAccepts')
                  }}</span>
                  <span
                    v-else-if="orderRefund.returnMoneySts === 3"
                    type="danger"
                  >{{
                    $t('order.buyShipment')
                  }}</span>
                  <span
                    v-else-if="orderRefund.returnMoneySts === 4"
                    type="danger"
                  >{{
                    $t('order.sellerReceipt')
                  }}</span>
                  <span
                    v-else-if="orderRefund.returnMoneySts === 5"
                    type="danger"
                  >{{
                    $t('order.refundsuccessfully')
                  }}</span>
                  <span
                    v-else-if="orderRefund.returnMoneySts === 6"
                    type="danger"
                  >{{
                    $t('order.withdrawsApplication')
                  }}</span>
                  <span
                    v-else
                    type="danger"
                  >{{ $t('order.refundClosed') }}</span>
                </div>
              </el-col>
              <el-col
                :span="$t('language') === 'English' ? 3 : 2"
                style="height: 100%"
              >
                <div class="item">
                  <div class="operate">
                    <div
                      class="default-btn text-btn"
                      @click="onViewOrderHandle(orderRefund.orderNumber)"
                    >
                      {{ $t('order.viewOrder') }}
                    </div>
                    <div
                      class="default-btn text-btn operate-btn"
                      @click="onToImbox(orderRefund)"
                    >
                      {{ $t('order.contactBuyer') }}
                    </div>
                    <div
                      v-if="![-1,2,5].includes(orderRefund.returnMoneySts)"
                      :class="[
                        'default-btn',
                        'text-btn',
                        $t('language') === 'English' ? 'lineHeight' : ''
                      ]"
                      @click="onRefundHandle(orderRefund.refundId, orderRefund.shopId)"
                    >
                      {{ $t('order.processingRefunds') }}
                    </div>
                    <div
                      v-if="[-1,2,5].includes(orderRefund.returnMoneySts)"
                      class="default-btn text-btn"
                      @click="onRefundHandle(orderRefund.refundId, orderRefund.shopId)"
                    >
                      {{ $t('order.lookRefunds') }}
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
        <div
          v-if="!dataList.length"
          class="empty"
        >
          {{ $t('order.noData') }}
        </div>
      </div>
    </div>
    <el-pagination
      v-if="dataList.length"
      :current-page="page.currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="page.pageSize"
      :total="page.total"
      layout="total, sizes, prev, pager, next, jumper"
      @update:page-size="onPageSizeChange"
      @update:current-page="onPageChange"
    />
    <!-- 弹窗  -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @refresh-data-list="refreshChange"
    />
    <order-info
      v-if="orderInfoVisible"
      ref="OrderInfoRef"
      @refresh-data-list="refreshChange"
    />
  </div>
</template>
<script setup>
import { ElMessage } from 'element-plus'
import AddOrUpdate from './add-or-update.vue'
import OrderInfo from '../order/add-or-update.vue'
import moment from 'moment'
import { useRoute } from 'vue-router'
const route = useRoute()

const options = [
  {
    value: 1,
    label: $t('order.buyerApplication')
  },
  {
    value: 2,
    label: $t('order.sellerAccepts')
  },
  {
    value: 3,
    label: $t('order.buyShipment')
  },
  {
    value: 4,
    label: $t('order.sellerReceipt')
  },
  {
    value: 5,
    label: $t('order.refundsuccessfully')
  },
  {
    value: -1,
    label: $t('order.refundClosed')
  }
]
const orderType = [
  {
    value: 0,
    label: $t('order.normalOrder')
  },
  {
    value: 1,
    label: $t('order.groupPurchaseOrder')
  },
  {
    value: 2,
    label: $t('order.spikeOrder')
  }
]
const refundType = [
  {
    value: 1,
    label: $t('order.wholeOrderRefund')
  },
  {
    value: 2,
    label: $t('order.singleItemRefund')
  }
]
const applyType = [
  {
    value: 1,
    label: $t('order.onlyRefund')
  },
  {
    value: 2,
    label: $t('order.refunds')
  }
]
const store = useCommonStore()

const sidebarFold = computed({
  get () {
    return store.sidebarFold
  },
  set (val) {
    store.updateSidebarFold(val)
  }
})
const searchForm = ref([])
const returnMoneySts = ref(null)
const page = ref({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
onActivated(() => {
  // 携带参数查询
  const query = route.query
  if (Object.keys(query).length > 0) {
    searchForm.value = route.query
    returnMoneySts.value = null
    onGetDataList(page.value)
  }
})
onMounted(() => {
  // 携带参数查询
  searchForm.value = route.query
  if (route.query.returnMoneySts) {
    returnMoneySts.value = Number(route.query.returnMoneySts)
  }
  onGetDataList(page.value)

  // 监听页面滚动
  window.addEventListener('scroll', onScrollToTop)
  // 监听屏幕宽度
  window.addEventListener('resize', onClientSize)
  onClientSize()
})
const productSpan = ref(8)
const onClientSize = () => {
  if ($t('language') === 'English') {
    productSpan.value = 7
    if (window.innerWidth < 1600) {
      productSpan.value = 6
    }
  } else {
    productSpan.value = 8
    if (window.innerWidth < 1600) {
      productSpan.value = 7
    }
  }
}
/**
 * 页面滚动事件
 */
const showHeadScroll = ref(false)
const onScrollToTop = () => {
  const scrollTop =
    window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
  showHeadScroll.value = scrollTop > 400
}

/**
 * 获取数据列表
 */
let tempSearchForm = null // 保存上次点击查询的请求条件
const sts = ref(0)
const dateRange = ref([])
const defaultTime = ref([
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59)
])
const dataList = ref([])
const onGetDataList = (pageParam, newData = false) => {
  const params = searchForm.value
  if (newData || !tempSearchForm) {
    tempSearchForm = {
      current: pageParam.currentPage,
      size: pageParam.pageSize,
      orderNumber: params ? (params.orderNumber ? params.orderNumber : null) : null,
      shopName: params ? (params.shopName ? params.shopName : null) : null,
      returnMoneySts: returnMoneySts.value || null,
      refundSn: params ? (params.refundSn ? params.refundSn : null) : null,
      orderType: params ? (params.orderType ? params.orderType : null) : null,
      applyType: params ? (params.applyType ? params.applyType : null) : null,
      refundType: params ? (params.refundType ? params.refundType : null) : null,
      startTime: dateRange.value ? (dateRange.value[0] ? dateRange.value[0] : null) : null, // 开始时间
      endTime: dateRange.value ? (dateRange.value[1] ? dateRange.value[1] : null) : null // 结束时间
    }
  } else {
    tempSearchForm.current = pageParam.currentPage
    tempSearchForm.size = pageParam.pageSize
    tempSearchForm.returnMoneySts = returnMoneySts.value || null
  }
  http({
    url: http.adornUrl('/order/refund/page'),
    method: 'get',
    params: http.adornParams(Object.assign(tempSearchForm))
  }).then(({ data }) => {
    dataList.value = data.records
    page.value.total = data.total
    sts.value = returnMoneySts.value || 0
  })
}
const onOrderRefundStatus = val => {
  returnMoneySts.value = val
}
// 每页数
const onPageSizeChange = val => {
  page.value.pageSize = val
  page.value.currentPage = 1
  onGetDataList(page.value)
}
// 当前页
const onPageChange = val => {
  page.value.currentPage = val
  onGetDataList(page.value)
}

/**
 * 导航选择状态
 */
const onSelectNav = e => {
  page.value.currentPage = 1
  const isSts = e.currentTarget.dataset.sts
  sts.value = parseInt(isSts)
  returnMoneySts.value = sts.value === 0 ? null : parseInt(isSts)
  onGetDataList(page.value)
}
/**
 * 查看订单
 */
const orderInfoVisible = ref(false)
const OrderInfoRef = ref(null)
const onViewOrderHandle = id => {
  orderInfoVisible.value = true
  nextTick(() => {
    OrderInfoRef.value?.init(id)
  })
}
/**
 * 处理退款
 */
const addOrUpdateVisible = ref(false)
const addOrUpdateRef = ref(null)
const onRefundHandle = (id, shopId) => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init(id, shopId)
  })
}
/**
 * 根据选项设置时间
 * 1:今天 2:昨天 3: 近七天 4:近30天 5:近60天
 */
const onSetDateRange = val => {
  let startDay = null
  let endDay = null
  if (val === 1) {
    startDay = 0
    endDay = 0
  } else if (val === 2) {
    startDay = -1
    endDay = -1
  } else if (val === 3) {
    startDay = -7
    endDay = -1
  } else if (val === 4) {
    startDay = -30
    endDay = -1
  } else {
    return
  }
  // 开始时间
  const startTime = moment().add(startDay, 'days').startOf('days').format('LL')
  // 结束时间
  const endTime = moment().add(endDay, 'days').endOf('days').format('LL')
  dateRange.value = [startTime, endTime]
}
// 清空按钮
const onResetSearch = () => {
  searchForm.value = {}
  dateRange.value = []
  returnMoneySts.value = null
}
// 刷新回调用
const refreshChange = () => {
  page.value.current = 1
  onGetDataList(page.value)
}
const onSearch = (newData = false) => {
  page.value.currentPage = 1
  page.value.pageSize = 10
  onGetDataList(page.value, newData)
}
// 前往消息盒子
const onToImbox = order => {
  if (order.userWriteOff) {
    ElMessage({
      message: $t('order.userlogoutTips'),
      type: 'error'
    })
    return
  }
  window.open(
    '/message-box/index?userId=' +
      order.userId +
      '&orderNumber=' +
      order.orderNumber,
    'view_window'
  )
}
onUnmounted(() => {
  // 页面销毁时移除监听
  window.removeEventListener('scroll', onScrollToTop)
  window.removeEventListener('resize', onClientSize)
})
</script>
<style lang="scss" scoped>
@use './index.scss';
</style>
